package main

import (
	"log"
	"os"
	"os/signal"
	"strconv"
	"syscall"

	tinyiotserver "gitee.com/mqyqingkong/tiny-iot-server"
)

func main() {
	server := tinyiotserver.NewServer(":7070")

	//只要有授权请求，就授权
	authMsgHandler := tinyiotserver.NewSimpleAuthMsgHandler(
		func(msg *tinyiotserver.Message) bool { return true }, nil)
	server.RegisterGlobalPreHandler(authMsgHandler)

	turnOnTheAirConditionerMsgHandler := &TurnOnTheAirConditionerMsgHandler{}
	server.RegisterHandler("Temperature", turnOnTheAirConditionerMsgHandler)

	//启动服务
	go server.Start()

	//
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	server.Close()
}

//处理温度事件,开空调
type TurnOnTheAirConditionerMsgHandler struct {
	tinyiotserver.MsgHandlerAdapter
}

func (h *TurnOnTheAirConditionerMsgHandler) OnReceive(requestMsg *tinyiotserver.Message) (newMsg *tinyiotserver.Message) {
	tag := "TurnOnTheAirConditionerMsgHandler"
	log.Printf("[%s] received msg:\n%s\n", tag, requestMsg)
	tmp := string(requestMsg.Body.Payload)
	tmp = tmp[0 : len(tmp)-1]
	tmpInt, err := strconv.Atoi(tmp)
	if err != nil {
		return tinyiotserver.FailMsg(string(requestMsg.Body.Topic), "Temperature content is not a number")
	}
	//温度>28度
	if tmpInt > 28 {
		newMsg = requestMsg.Copy()
		//生成空调消息（指令）
		newMsg.SetTopic("AirConditioner")
		newMsg.SetPayload([]byte("26C"))
		log.Printf("[%s] generate TurnOnAirConditioner msg:\n%s\n", tag, newMsg)
	}
	return
}
